<template>
  <div class="box">
    <el-card shadow class="card">
      <!-- 1.面包屑 -->
      <MyBread url="administrator" level1="车辆管理" />
      <!-- 2.搜索 -->
      <el-input
        placeholder="请输入车牌号"
        v-model="search"
        class="with-input"
        clearable
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="searchUser"
        ></el-button>
      </el-input>
      <!-- 添加车辆按钮 -->
      <el-button type="success" plain @click="dialogVisible"
        >添加车辆</el-button
      >
      <!-- 3.表格 -->
      <el-table :data="UserData" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="40"></el-table-column>
        <el-table-column prop="carNumber" label="车辆名"></el-table-column>
        <el-table-column prop="logonDate" label="注册日期"></el-table-column>
        <el-table-column
          prop="insuranceDate"
          label="保险日期"
        ></el-table-column>
        <el-table-column prop="validDate" label="有效日期"></el-table-column>
        <el-table-column prop="scrapDate" label="报废日期"></el-table-column>
        <el-table-column prop="appointDate" label="预约日期"></el-table-column>
        <el-table-column prop="useCount" label="使用次数"></el-table-column>
        <el-table-column label="是否预约" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isUse"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="已预约"
              inactive-text="未预约"
              disabled
              class="switch"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="310">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="hendleEdit(scope.$index, scope.row)"
              style="margin-right: 10px"
            ></el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除该车辆信息吗？"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <el-button
                slot="reference"
                type="danger"
                circle
                icon="el-icon-delete"
              >
              </el-button>
            </el-popconfirm>
            <el-button
              type="info"
              size="mini"
              @click="hendleDistribute(scope.$index, scope.row)"
              class="distribution-button"
              >分配教练</el-button
            >
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定取消分配吗？"
              @confirm="handleCancelDistribute(scope.$index, scope.row)"
            >
              <el-button
                slot="reference"
                size="mini"
                class="cancel-distribution-button"
                >取消分配
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 4.分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="length"
      >
      </el-pagination>
    </el-card>
    <!-- 添加车辆的对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="440px">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item prop="carNumber">
          <el-input v-model="form.carNumber" placeholder="车辆名"></el-input>
        </el-form-item>
        <el-form-item prop="logonDate">
          <el-date-picker
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
            v-model="form.logonDate"
            type="date"
            placeholder="注册日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="insuranceDate">
          <el-date-picker
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
            v-model="form.insuranceDate"
            type="date"
            placeholder="保险日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="validDate">
          <el-date-picker
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
            v-model="form.validDate"
            type="date"
            placeholder="有效日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
            v-model="form.scrapDate"
            type="date"
            placeholder="报废日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="handleUser">保存信息</el-button>
      </div>
    </el-dialog>
    <!-- 分配教练对话框 -->
    <el-dialog
      title="请选择分配教练"
      :visible.sync="getDistributeVisible"
      width="440px"
    >
      <div style="width: 100%">
        <el-select v-model="Coach" placeholder="请选择教练" style="width: 100%">
          <el-option
            v-for="item in coachName"
            :key="item.identify"
            :label="item.name"
            :value="item.identify"
          >
          </el-option>
        </el-select>
      </div>
      <div slot="footer">
        <el-button @click="getDistributeVisible = false">取 消</el-button>
        <el-button type="primary" @click="distributeCoach()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      search: "", // 搜索输入框输入的内容
      isAdd: true, // true：添加 false：删除
      page: 1, // 当前页数
      limit: 2, // 每条页面条数
      length: 0, // 获取数据的长度
      dialogFormVisible: false, // 控制车辆对话框的显示与隐藏
      getDistributeVisible: false, // 分配教练对话框的显示与隐藏
      UserData: [], // 请求获取的车辆数据
      coachName: [], // 教练名
      Coach: "", // 分配的教练名
      singleRow: {}, // 被选中的一条车辆数据
      // 车辆表单
      form: {
        carNumber: "", // 车牌号
        logonDate: "", // 注册日期
        insuranceDate: "", // 保险日期
        validDate: "", // 有效期
        scrapDate: "", // 报废日期
        isUse: false, // 是否被预约
        appointDate: "", // 预约日期（最近一次）
        useCount: 0, // 使用次数
      },
      // 车辆表单验证规则
      rules: {
        carNumber: [
          { required: true, message: "车辆名不能为空", trigger: "blur" },
        ],
        logonDate: [
          { required: true, message: "注册日期不能为空", trigger: "change" },
        ],
        insuranceDate: [
          { required: true, message: "保险日期不能为空", trigger: "change" },
        ],
        validDate: [
          { required: true, message: "有效日期不能为空", trigger: "change" },
        ],
      },
      title: "", // 对话框标题
    };
  },
  methods: {
    // 取消更新或添加
    cancel() {
      this.dialogFormVisible = false;
      if (this.isAdd) {
        this.form = { isUse: false, appointDate: "", useCount: 0 };
      } else {
        this.getCarList();
        this.getCarListDataLength();
      }
    },
    // 获取列表数据总长度
    getCarListDataLength() {
      this.$https.getCar({ like: this.search }).then((res) => {
        this.length = res.data.length;
      });
    },
    // 搜索功能实现
    searchUser() {
      this.getCarListDataLength();
      this.limit = 2;
      this.page = 1;
      this.getCarList();
      this.search = "";
    },
    // 获取车辆数据
    async getCarList() {
      const { data } = await this.$https.getCar({
        page: this.page,
        limit: this.limit,
        like: this.search,
      });
      this.UserData = data;
    },
    // 当每页条数发生变化使调用
    handleSizeChange(val) {
      this.limit = val;
      this.page = 1;
      this.getCarList();
    },
    // 当页数发生变化时调用
    handleCurrentChange(val) {
      this.page = val;
      this.getCarList();
    },
    // 显示添加车辆的对话框 （添加车辆权限）
    async dialogVisible() {
      // 权限验证
      if (!(await this.haveThisPermission(this.$route.path, "添加车辆"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      // 清空表单
      this.form = { isUse: false, appointDate: "", useCount: 0 };
      // 显示添加车辆对话框
      this.isAdd = true;
      this.title = "添加车辆信息";
      this.dialogFormVisible = true;
    },
    // 添加车辆信息到json-server数据库
    addUser() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          // 发送数据
          await this.$https.addUserData("/cars", this.form);
          // 重新获取车辆数据
          this.page = 1;
          this.search = "";
          this.getCarList();
          // 重新获取车辆长度
          this.getCarListDataLength();
          // 清空表单
          this.form = { isUse: false, appointDate: "", useCount: 0 };
          // 提示信息
          this.$message.success("车辆添加成功");
        } else {
          this.$message.warning("表单验证信息不通过");
        }
      });
    },
    // 根据id更新车辆信息到json-server数据库
    updateUser() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          // 更新车辆数据
          await this.$https.updateUserData("/cars", this.form.id, this.form);
          // 重新获取车辆数据
          this.page = 1;
          this.search = "";
          this.getCarList();
          // 清空表单
          this.form = { isUse: false, appointDate: "", useCount: 0 };
          // 提示信息
          this.$message.success("修改车辆成功");
        } else {
          this.$message.info("表单验证信息不通过");
        }
      });
    },
    // 删除车辆（删除车辆权限）
    async handleDelete(_, row) {
      if (!(await this.haveThisPermission(this.$route.path, "删除车辆"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      await this.$https.deleteUserData("/cars", row.id);
      // 重新获取车辆数据
      this.page = 1;
      this.search = "";
      this.getCarList();
      this.getCarListDataLength();
      // 提示信息
      this.$message.success("车辆删除成功");
    },
    // 确定是添加还是编辑操作
    handleUser() {
      if (this.isAdd) {
        this.addUser();
      } else {
        this.updateUser();
      }
    },
    // 编辑车辆信息（修改车辆权限）
    async hendleEdit(_, row) {
      if (!(await this.haveThisPermission(this.$route.path, "修改车辆"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      this.isAdd = false;
      this.title = "编辑车辆信息";
      this.form = row;
      this.dialogFormVisible = true;
    },
    // 分配教练
    async distributeCoach() {
      if (this.Coach === "") {
        this.$message.info("请选择教练");
      } else {
        // 更新车辆数据
        this.singleRow.isUse = true;
        this.singleRow.useCount++;
        // 修改预约日期
        let date = new Date(new Date().getTime() + 3600 * 1000 * 24);
        this.singleRow.appointDate =
          date.getFullYear() +
          "-" +
          (date.getMonth() + 1) +
          "-" +
          date.getDate();
        await this.$https.updateUserData(
          "/cars",
          this.singleRow.id,
          this.singleRow
        );
        // 获取对应教练数据
        const { data } = await this.$https.getUserData({
          url: "/coach",
          identify: this.Coach,
        });
        // 更新教练数据
        data[0].reverseCar = this.singleRow.carNumber;
        await this.$https.updateUserData("/coach", data[0].id, data[0]);
        this.Coach = "";
        this.singleRow = {};
        this.getDistributeVisible = false;
        this.$message.success("分配教练成功");
      }
    },
    // 取消分配（取消分配权限）
    async handleCancelDistribute(_, row) {
      if (!(await this.haveThisPermission(this.$route.path, "取消分配"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      if (row.isUse) {
        this.getDistributeVisible = false;
        // 若预约的时间已经过去，使用次数不需要减少，未过则减少
        if (new Date(row.appointDate).getTime() > Date.now()) {
          row.useCount--;
        }
        // 更新车辆数据
        row.isUse = false;
        row.appointDate = "";
        await this.$https.updateUserData("/cars", row.id, row);
        // 获取对应教练数据
        const { data } = await this.$https.getCoachInfoByReverseCar(
          row.carNumber
        );
        // 更新教练数据
        data[0].reverseCar = "";
        await this.$https.updateUserData("/coach", data[0].id, data[0]);
        this.$message.success("取消分配教练成功");
      } else {
        this.$message.info("未分配教练");
      }
    },
    // 按钮处理分配教练（分配教练权限）
    async hendleDistribute(_, row) {
      if (!(await this.haveThisPermission(this.$route.path, "分配教练"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      if (row.isUse) {
        this.$message.info("已分配教练");
      } else {
        this.singleRow = row;
        this.getDistributeVisible = true;
      }
    },
  },
  async mounted() {
    // 获取所有教练名
    this.$https.getUserData({ url: "/coach" }).then((res) => {
      res.data.forEach((element) => {
        this.coachName.push({
          identify: element.identify,
          name: element.name,
        });
      });
    });
    // 新的一天来临，重置车辆数据
    const { data: AllCars } = await this.$https.getUserData({ url: "/cars" });
    const hasAppointDateCars = AllCars.filter(
      (item) => item.appointDate !== ""
    );
    if (hasAppointDateCars.length !== 0) {
      hasAppointDateCars.forEach(async (item) => {
        if (item.isUse && new Date(item.appointDate) < Date.now()) {
          item.appointDate = "";
          item.isUse = false;
          await this.$https.updateUserData("/cars", item.id, item);
          // 修改预约车辆的教练数据
          const { data: useCarCoach } =
            await this.$https.getCoachInfoByReverseCar(item.carNumber);
          useCarCoach[0].reverseCar = "";
          await this.$https.updateUserData(
            "/coach",
            useCarCoach[0].id,
            useCarCoach[0]
          );
        }
      });
    }
    // 获取车辆信息总长度
    this.getCarListDataLength();
    // 获取车辆数据
    this.getCarList();
  },
};
</script>

<style scoped>
.box,
.card {
  height: 100%;
}
.with-input {
  width: 500px;
  margin-top: 30px;
  margin-bottom: 30px;
  margin-right: 10px;
}
.pagination {
  margin-top: 30px;
}
.distribution-button {
  margin-left: 10px;
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
}
.cancel-distribution-button {
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}
</style>